package com.tools.gateway.filter;

import com.tools.common.core.util.CheckResult;
import com.tools.common.core.util.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * 鉴权
 * @Author 小柒2012
 * @Date 2020/6/12
 */
@Configuration
public class AuthFilter implements GlobalFilter, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(AuthFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst("token");
        String path = exchange.getRequest().getPath().toString();
        /**
         * 排除过滤
         */
        if(patterns.contains(path)){
            return chain.filter(exchange);
        }
        /**
         * 判断 token 是否为空
         */
        if (StringUtils.isBlank(token)) {
            logger.info( "token is empty..." );
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }else{
            /**
             * 验证真伪
             */
            CheckResult checkResult = JwtUtils.validateJWT(token);
            if (!checkResult.isSuccess()) {
                logger.info( "token is error..." );
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100;
    }

    private  static List<String> patterns =
            Arrays.asList(new String[] {"/api/sys/login","/error",
                    "/api/sys/v2/api-docs","/api/meizi/v2/api-docs"});
}